package com.realife.eson.common.util.reg;

import com.realife.eson.common.asserts.AssertNP;
import org.apache.commons.lang3.StringUtils;

import java.util.HashSet;
import java.util.Set;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * @version V1.0
 * @author: guangcheng
 * @date: 2021/5/22 20:18
 * @description:
 */
public class RegUtils {
    private RegUtils() {
    }

    /**
     * @param regStr  正则表达式
     * @param content 要解析的内容
     * @return
     */
    public static Matcher getMatcher(String regStr, String content) {
        Pattern pattern = Pattern.compile(regStr);
        if (!StringUtils.isEmpty(content)) {
            Matcher matcher = pattern.matcher(content);
            return matcher;
        }
        return null;
    }


    /**
     * @param content
     * @return
     */
    public static Set<String> findUrlSetFromTextOrStr(String content) {
        Set<String> urlSet = new HashSet<>();
        String regStrHttp = "((http[s]{0,1})://)(([a-zA-Z0-9\\._-]+\\.[a-zA-Z]{2,6})|([0-9]{1,3}\\.[0-9]{1,3}\\.[0-9]{1,3}\\.[0-9]{1,3}))(:[0-9]{1,4})*(/[a-zA-Z0-9\\&%_\\./-~-]*)?";

        if (!StringUtils.isEmpty(content)) {
            Matcher matcher = getMatcher(regStrHttp, content);
            while (matcher.find()) {
                String url = matcher.group(0);
                urlSet.add(url);
            }
        }
        return urlSet;
    }


    /**
     * 自定义正则模式
     *
     * @param content
     * @param regMod
     * @return
     */
    public static Set<String> findUrlSetFromTextOrStr(String content, String regMod) {
        Set<String> urlSet = new HashSet<>();
        if (!StringUtils.isEmpty(content)) {
            Matcher matcher = getMatcher(regMod, content);
            while (matcher.find()) {
                String url = matcher.group(0);
                urlSet.add(url);
            }
        }

        return urlSet;
    }


    /**
     * 字符串是否符合规则
     *
     * @param regMod
     * @param content
     * @return
     */
    public static boolean check(String regMod, String content) {
        boolean flag = false;
        try {
            Matcher matcher = getMatcher(regMod, content);
            if (AssertNP.legalParams(matcher)) {
                flag = matcher.matches();
            }
        } catch (Exception e) {
            flag = false;
        }
        return flag;
    }


    public static void main(String[] args) {
        boolean check = check("((http[s]{0,1})://)(([a-zA-Z0-9\\._-]+\\.[a-zA-Z]{2,6})|([0-9]{1,3}\\.[0-9]{1,3}\\.[0-9]{1,3}\\.[0-9]{1,3}))(:[0-9]{1,4})*(/[a-zA-Z0-9\\&%_\\./-~-]*)?", "http://www.baidu.com");
        System.out.println("check = " + check);
    }

}

